{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python类与面向对象编程基础\n",
    "\n",
    "## 课程介绍\n",
    "\n",
    "欢迎来到Python类与面向对象编程基础课程！本课程专为编程初学者设计，通过简单易懂的例子，帮助您理解Python中的类和对象概念。\n",
    "\n",
    "### 学习目标\n",
    "- 理解面向对象编程的基本概念\n",
    "- 学会创建和使用Python类\n",
    "- 掌握类的属性和方法\n",
    "- 了解继承和多态等高级概念\n",
    "\n",
    "让我们开始吧！"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第1节：什么是面向对象编程？\n",
    "\n",
    "面向对象编程（Object-Oriented Programming，简称OOP）是一种编程范式，它使用\"对象\"这一概念来组织代码。\n",
    "\n",
    "### 核心概念\n",
    "\n",
    "1. **类（Class）**：类是创建对象的\"蓝图\"或\"模板\"，定义了对象可能具有的属性和方法。\n",
    "2. **对象（Object）**：对象是类的实例，具有类定义的属性和方法。\n",
    "3. **属性（Attributes）**：属性是对象的特征或状态，例如汽车的颜色、速度等。\n",
    "4. **方法（Methods）**：方法是对象可以执行的操作或行为，例如汽车可以加速、刹车等。\n",
    "\n",
    "### 现实生活中的类和对象\n",
    "\n",
    "想象一下：\n",
    "- **类**：汽车的设计图纸\n",
    "- **对象**：根据设计图纸制造的实际汽车\n",
    "- **属性**：汽车的颜色、型号、速度\n",
    "- **方法**：启动、加速、刹车"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第2节：创建第一个Python类\n",
    "\n",
    "在Python中，我们使用`class`关键字来创建类。让我们创建一个简单的`Person`类："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Person:\n",
    "    \"\"\"这是一个简单的Person类\"\"\"\n",
    "    \n",
    "    # 这是一个类属性，所有实例共享\n",
    "    species = \"人类\"\n",
    "    \n",
    "    # 初始化方法（构造函数）\n",
    "    def __init__(self, name, age):\n",
    "        # 这些是实例属性，每个实例独有\n",
    "        self.name = name  # 姓名\n",
    "        self.age = age    # 年龄\n",
    "    \n",
    "    # 实例方法\n",
    "    def say_hello(self):\n",
    "        \"\"\"打招呼方法\"\"\"\n",
    "        aa=1\n",
    "        return f\"你好，我是{self.name}，今年{self.age}岁。\"\n",
    "    \n",
    "    def have_birthday(self):\n",
    "        \"\"\"过生日，年龄增加1\"\"\"\n",
    "        self.age += 1\n",
    "        return f\"{self.name}过生日了，现在{self.age}岁了！\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 代码解析\n",
    "\n",
    "1. **类定义**：`class Person:`创建了一个名为`Person`的类。\n",
    "2. **类文档字符串**：`\"\"\"这是一个简单的Person类\"\"\"`是类的文档说明。\n",
    "3. **类属性**：`species = \"人类\"`是所有`Person`实例共享的属性。\n",
    "4. **初始化方法**：`__init__`是特殊方法，创建对象时自动调用。\n",
    "5. **实例属性**：`self.name`和`self.age`是每个实例独有的属性。\n",
    "6. **实例方法**：`say_hello()`和`have_birthday()`是实例可以调用的方法。\n",
    "7. **self参数**：所有实例方法的第一个参数都是`self`，代表实例本身。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第3节：创建和使用对象\n",
    "\n",
    "让我们创建`Person`类的几个实例（对象）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "小明的年龄是: 18岁\n",
      "小红的年龄是: 17岁\n",
      "小明是: 人类\n",
      "小红是: 人类\n",
      "你好，我是小明，今年18岁。\n",
      "你好，我是小红，今年17岁。\n",
      "小明过生日了，现在19岁了！\n",
      "现在小明的年龄是: 19岁\n"
     ]
    }
   ],
   "source": [
    "# 创建Person类的实例\n",
    "xiaoming = Person(\"小明\", 18)\n",
    "xiaohong = Person(\"小红\", 17)\n",
    "\n",
    "# 访问实例属性  xiaoming.age\n",
    "print(f\"小明的年龄是: {xiaoming.age}岁\")\n",
    "print(f\"小红的年龄是: {xiaohong.age}岁\")\n",
    "\n",
    "# 访问类属性\n",
    "print(f\"小明是: {xiaoming.species}\")\n",
    "print(f\"小红是: {xiaohong.species}\")\n",
    "\n",
    "# 调用实例方法\n",
    "print(xiaoming.say_hello())\n",
    "print(xiaohong.say_hello())\n",
    "\n",
    "# 小明过生日\n",
    "print(xiaoming.have_birthday())\n",
    "print(f\"现在小明的年龄是: {xiaoming.age}岁\")\n",
    "print(f\"现在小红的年龄是: {xiaohong.age}岁\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 动手练习\n",
    "\n",
    "创建一个新的`Person`对象，代表你自己，并尝试调用各种方法："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 在这里创建代表你自己的Person对象\n",
    "myself = Person(\"你的名字\", 20)\n",
    "\n",
    "# 调用say_hello方法\n",
    "print(myself.say_hello())\n",
    "\n",
    "# 调用have_birthday方法\n",
    "print(myself.have_birthday())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第4节：类的属性详解\n",
    "\n",
    "Python类中有两种主要类型的属性：\n",
    "\n",
    "1. **实例属性**：属于每个对象实例，可以有不同的值\n",
    "2. **类属性**：属于类本身，所有实例共享同一个值\n",
    "\n",
    "让我们通过例子来理解："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Student:\n",
    "    # 类属性\n",
    "    school = \"蓝天小学\"  # 所有学生都在同一所学校\n",
    "    count = 0          # 学生计数器\n",
    "    \n",
    "    def __init__(self, name, grade):\n",
    "        # 实例属性\n",
    "        self.name = name    # 学生姓名\n",
    "        self.grade = grade  # 学生年级\n",
    "        \n",
    "        # 更新类属性\n",
    "        Student.count += 1  # 每创建一个学生，计数器加1\n",
    "    \n",
    "    def introduce(self):\n",
    "        \"\"\"自我介绍\"\"\"\n",
    "        return f\"我叫{self.name}，是{self.school}{self.grade}年级的学生。\"\n",
    "\n",
    "# 创建学生对象\n",
    "student1 = Student(\"张三\", 3)\n",
    "student2 = Student(\"李四\", 2)\n",
    "student3 = Student(\"王五\", 3)\n",
    "\n",
    "# 访问实例属性\n",
    "print(f\"{student1.name}在{student1.grade}年级\")\n",
    "print(f\"{student2.name}在{student2.grade}年级\")\n",
    "\n",
    "# 访问类属性\n",
    "print(f\"所有学生都在{Student.school}\")\n",
    "print(f\"总共有{Student.count}名学生\")\n",
    "\n",
    "# 通过实例访问类属性也是可以的\n",
    "print(f\"通过实例访问：{student1.school}\")\n",
    "\n",
    "# 修改类属性\n",
    "Student.school = \"阳光小学\"  # 学校改名了\n",
    "print(f\"学校改名后：{student1.school}\")\n",
    "print(f\"学校改名后：{student2.school}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 注意事项\n",
    "\n",
    "- 实例属性通常在`__init__`方法中使用`self.属性名`定义\n",
    "- 类属性直接在类内部定义，不使用`self`\n",
    "- 修改类属性应使用`类名.属性名`，而不是`实例.属性名`\n",
    "- 如果使用`实例.属性名`赋值，会创建一个新的实例属性，而不是修改类属性"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第5节：类的方法详解\n",
    "\n",
    "Python类中有三种主要类型的方法：\n",
    "\n",
    "1. **实例方法**：操作实例属性，第一个参数是`self`\n",
    "2. **类方法**：操作类属性，使用`@classmethod`装饰器，第一个参数是`cls`\n",
    "3. **静态方法**：不操作实例或类属性，使用`@staticmethod`装饰器，没有特殊的第一个参数\n",
    "\n",
    "让我们看一个综合例子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Calculator:\n",
    "    # 类属性\n",
    "    name = \"超级计算器\"\n",
    "    version = \"1.0\"\n",
    "    calculation_count = 0  # 记录计算次数\n",
    "    \n",
    "    def __init__(self, owner):\n",
    "        # 实例属性\n",
    "        self.owner = owner  # 计算器拥有者\n",
    "        self.last_result = 0  # 上次计算结果\n",
    "    \n",
    "    # 实例方法\n",
    "    def add(self, a, b):\n",
    "        \"\"\"加法运算\"\"\"\n",
    "        self.last_result = a + b\n",
    "        Calculator.calculation_count += 1  # 更新计算次数\n",
    "        return self.last_result\n",
    "    \n",
    "    def subtract(self, a, b):\n",
    "        \"\"\"减法运算\"\"\"\n",
    "        self.last_result = a - b\n",
    "        Calculator.calculation_count += 1  # 更新计算次数\n",
    "        return self.last_result\n",
    "    \n",
    "    # 类方法\n",
    "    @classmethod\n",
    "    def get_info(cls):\n",
    "        \"\"\"获取计算器信息\"\"\"\n",
    "        return f\"{cls.name} v{cls.version}\"\n",
    "    \n",
    "    @classmethod\n",
    "    def update_version(cls, new_version):\n",
    "        \"\"\"更新版本号\"\"\"\n",
    "        cls.version = new_version\n",
    "        return f\"版本已更新为{cls.version}\"\n",
    "    \n",
    "    # 静态方法\n",
    "    @staticmethod\n",
    "    def is_even(number):\n",
    "        \"\"\"判断一个数是否为偶数\"\"\"\n",
    "        return number % 2 == 0\n",
    "    \n",
    "    @staticmethod\n",
    "    def pi():\n",
    "        \"\"\"返回圆周率π的值\"\"\"\n",
    "        return 3.14159\n",
    "\n",
    "# 创建计算器对象\n",
    "my_calc = Calculator(\"小明\")\n",
    "your_calc = Calculator(\"小红\")\n",
    "\n",
    "# 调用实例方法\n",
    "print(f\"5 + 3 = {my_calc.add(5, 3)}\")\n",
    "print(f\"10 - 4 = {your_calc.subtract(10, 4)}\")\n",
    "print(f\"小明的上次计算结果：{my_calc.last_result}\")\n",
    "print(f\"小红的上次计算结果：{your_calc.last_result}\")\n",
    "\n",
    "# 调用类方法\n",
    "print(Calculator.get_info())\n",
    "print(Calculator.update_version(\"2.0\"))\n",
    "print(my_calc.get_info())  # 通过实例也可以调用类方法\n",
    "\n",
    "# 调用静态方法\n",
    "print(f\"7是偶数吗？{Calculator.is_even(7)}\")\n",
    "print(f\"8是偶数吗？{my_calc.is_even(8)}\")\n",
    "print(f\"π的值约为{Calculator.pi()}\")\n",
    "\n",
    "# 查看计算次数\n",
    "print(f\"总共进行了{Calculator.calculation_count}次计算\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
